package coroutines

import kotlinx.coroutines.*
import java.util.concurrent.atomic.AtomicInteger
import kotlin.system.measureTimeMillis

suspend fun massiveRun(action : suspend ()->Unit){
    val n  =100
    val k = 1000
    val time = measureTimeMillis {
        coroutineScope {
            repeat(n){
                launch {
                    repeat(k){
                        action()
                    }
                }
            }
        }
    }
    println("complete ${n * k} actions in ${time} ms")
}

fun main(){
    /*var counter = AtomicInteger(0)
    runBlocking {
        withContext(Dispatchers.Default){
            massiveRun {
                counter.incrementAndGet()
            }
        }
        println("Counter = ${counter.get()}")
    }*/

    //限制线程 是解决共享可变状态问题的一种方案
    var counter = 0
    val counterContext = newSingleThreadContext("CounterContext")
    runBlocking {
        withContext(Dispatchers.Default){
            massiveRun {
                withContext(counterContext){
                    counter++
                }
            }
        }
        println("Counter = ${counter}")
    }
}